import React, { useState } from 'react';
import { Button, Table, Modal, message, Input,Form } from 'antd';
import './index.scss'
import { useEffect } from 'react';
import { getUsers } from '../../../utils/request';
import { addUser,request } from '../../../utils/request';
const { Search } = Input;

const UserMg = () => {
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [selectedUser, setSelectedUser] = useState(null);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [showCheckbox, setShowCheckbox] = useState(false);
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const [userData, setUserData] = useState([]);
    // 新增状态和表单实例（在useState部分）
    const [isAddModalVisible, setIsAddModalVisible] = useState(false);
    const [addForm] = Form.useForm(); // 用于表单校验和数据收集
    
   

    useEffect(() => {
        getUsers('user')
            .then(data => {
                setUserData(data);
            })
            .catch(err => {
                console.error(err);
                message.error('获取用户数据失败');
            });
    }, []);
    const handleAdd = () => {
        setIsAddModalVisible(true);
    };

    const handleAddUser = async () => {
        try {
            // 校验并获取表单数据
            const values = await addForm.validateFields();
            // 调用封装的请求方法
            const response = await request.post('/api/users', values); 
            if (response.success) {
                message.success('用户添加成功');
                setIsAddModalVisible(false); // 关闭弹窗
                // 刷新用户列表
                getUsers('user'); 
            }
        } catch (error) {
            message.error('用户添加失败：' + (error.response?.data?.message || '网络错误'));
        }
    };

    const handleDelete = async () => {
        if (showCheckbox) {
            if (selectedRowKeys.length === 0) {
                message.warning('请选择要删除的用户');
                return;
            }
            try {
                // 调用删除接口（假设后端接口为/api/users/{userId}）
                const deletePromises = selectedRowKeys.map(async (userId) => {
                    await request.delete(`/api/users/${userId}`);
                });
                await Promise.all(deletePromises);
                
                // 删除成功后刷新用户列表
                const freshData = await getUsers('user');
                setUserData(freshData);
                
                message.success(`成功删除 ${selectedRowKeys.length} 条用户记录`);
            } catch (error) {
                message.error('删除失败：' + (error.response?.data?.message || '网络错误'));
            } finally {
                setShowCheckbox(false);
                setSelectedRowKeys([]);
            }
        } else {
            setShowCheckbox(true);
        }
    };

    const handleMore = (record) => {
        setSelectedUser(record);
        setIsModalVisible(true);
    };

    const handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };

    const handleReset = (clearFilters) => {
        clearFilters();
        setSearchText('');
    };

    const columns = [
        { title: 'ID', dataIndex: 'id', key: 'id' },
        { title: '用户名', dataIndex: 'username', key: 'username'},
        { title: '邮箱', dataIndex: 'email', key: 'email' },
        { title: '注册时间', dataIndex: 'joinDate', key: 'joinDate' },
        { title: '用户权限', dataIndex: 'role', key: 'role' },
        { 
            title: '更多', 
            key: 'more', 
            render: (_, record) => (
                <a style={{ color: 'blue' }} onClick={() => handleMore(record)}>
                    更多
                </a>
            ),
        },
    ];

    const [data, setData] = useState(Array.from({ length: 100 }, (_, index) => ({
        key: index,
        id: index + 1,
        username: `用户${index + 1}`,
        email: `user${index + 1}@example.com`,
        joinDate: '2023-01-01',
        permission: '普通',
    })));

    const rowSelection = {
        selectedRowKeys,
        onChange: (keys) => {
            setSelectedRowKeys(keys);
        },
        columnWidth: '50px',
        hideDefaultSelections: true,
        selections: [],
        preserveSelectedRowKeys: false,
    };

    return (
        <div>
            <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                    <Button onClick={handleAdd} >添加</Button>
                    <Button
                        style={{ marginLeft: 8, backgroundColor: showCheckbox && selectedRowKeys.length > 0 ? 'red' : '', color: showCheckbox && selectedRowKeys.length > 0 ? 'white' : '' }}
                        onClick={handleDelete}
                    >
                        {showCheckbox ? '确认删除' : '删除'}
                    </Button>
                </div>
                <div style={{ width: 200 }}>
                    <Search
                        placeholder="搜索用户名"
                        value={searchText}
                        onChange={(e) => setSearchText(e.target.value)}
                        onPressEnter={(e) => handleSearch([e.target.value], () => {}, 'username')}
                        styles={{
                            input: {
                                height: 32,
                            }
                         }}
                    />
                </div>
            </div>
            <Modal
            title="添加新用户"
            visible={isAddModalVisible}
            onOk={handleAddUser}
            onCancel={() => setIsAddModalVisible(false)}
            okText="提交"
            cancelText="取消"
            >
            <Form form={addForm} layout="vertical">
                <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
                style={{ width: '77%' }}
                >
                <Input placeholder="请输入用户名" />
                </Form.Item>
                <Form.Item
                name="password"
                label="密码"
                rules={[{ required: true, message: '请输入密码' }]}
                style={{ width: '80%' }}
                >
                <Input.Password placeholder="请输入密码" />
                </Form.Item>
                <Form.Item
                name="email"
                label="邮箱"
                rules={[
                    { required: true, message: '请输入邮箱' },
                    { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
                style={{ width: '80%' }}
                >
                <Input placeholder="请输入邮箱" />
                </Form.Item>
            </Form>
            </Modal>
            <Table
                columns={columns}
                dataSource={userData.filter(record =>
                    record.username.toString().toLowerCase().includes(searchText.toLowerCase())
                )}
                pagination={{ pageSize: 20 }}
                rowSelection={showCheckbox ? rowSelection : null}
            />
            <Modal
                title="用户详情"
                visible={isModalVisible}
                onCancel={() => setIsModalVisible(false)}
                footer={null}
            >
                {selectedUser && (
                    <div>
                        <p>ID: {selectedUser.id}</p>
                        <p>用户名: {selectedUser.username}</p>
                        <p>邮箱: {selectedUser.email}</p>
                        <p>注册时间: {selectedUser.joinDate}</p>
                        <p>用户权限: {selectedUser.permission}</p>
                    </div>
                )}
            </Modal>
        </div>
    );
};

export default UserMg;